package com.park.dailytool.task;

import com.google.common.collect.Lists;
import com.park.dailytool.base.AjaxResult;
import com.park.dailytool.base.DateUtil;
import com.park.dailytool.base.MailService;
import com.park.dailytool.base.poi.ExcelUtil;
import com.park.dailytool.data.dao.jpa.local.EveryDayAmountJpaDao;
import com.park.dailytool.data.pojo.model.local.EveryDayAmount;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author huangding
 * @description
 * @date 2019/3/13 15:43
 */
@Component
@Slf4j
public class LinHaiTask {

    @Autowired
    private EveryDayAmountJpaDao everyDayAmountJpaDao;

    @Autowired
    private MailService mailService;

    /**
     * 保存每天财务的数据
     */
    @Scheduled(cron = "0 0/2 16 * * ?")
    public void sendEmail() {
        log.info("定时器开始");
        EveryDayAmount everyDayAmount = everyDayAmountJpaDao
            .findByDate(LocalDate.now().minusDays(3).toString());
        ExcelUtil<EveryDayAmount> util = new ExcelUtil<>(EveryDayAmount.class);
        List<EveryDayAmount> everyDayAmounts = Lists.newArrayList();
        everyDayAmounts.add(everyDayAmount);
        AjaxResult amountExcel2 = util.exportExcel(everyDayAmounts, "财务数据", null, null);
        ByteArrayOutputStream msg2 = (ByteArrayOutputStream) amountExcel2.get("msg");

        String exportFileName = DateUtil.nowDateTimeString() + ".xlsx";
        mailService.sendHTMLAndInlineFileMsg(LocalDateTime.now().toLocalDate().toString() + "-金额数据",
            LocalDateTime.now().toLocalDate().toString() + "当天金额数据",
            exportFileName,
            workbookConvertorStream(msg2), "2402090592@qq.com");
    }

    public static InputStream workbookConvertorStream(ByteArrayOutputStream out) {
        InputStream in = null;
        try {
            byte[] bookByteAry = out.toByteArray();
            in = new ByteArrayInputStream(bookByteAry);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return in;
    }
}
